package com.xdxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdxc.exception.CustomException;
import com.xdxc.mapper.ExamsMapper;
import com.xdxc.model.dto.ExamDto;
import com.xdxc.model.dto.ExamQueryDTO;
import com.xdxc.model.dto.ExamSubmitDto;
import com.xdxc.model.entity.Exams;
import com.xdxc.model.form.ExamsForm;
import com.xdxc.service.ExamsService;
import com.xdxc.utils.DateTimeUtils;
import com.xdxc.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.xdxc.utils.DateTimeUtils.DATE_FORMAT;

@Service
public class ExamsServiceImpl extends ServiceImpl<ExamsMapper, Exams> implements ExamsService {



    @Autowired
    private RedisService redisService;
    @Override
    public Page<Exams> pageExams(ExamQueryDTO queryDTO) {
        return this.lambdaQuery()
                .like(StringUtils.isNotBlank(queryDTO.getTitle()), Exams::getTitle, queryDTO.getTitle())
                .eq(queryDTO.getState() != null, Exams::getState, queryDTO.getState())
                .between(queryDTO.getStartTime() != null && queryDTO.getEndTime() != null,
                        Exams::getCreateTime, queryDTO.getStartTime(), queryDTO.getEndTime())
                .page(new Page<>(queryDTO.getPage(), queryDTO.getSize()));
    }

    /**
     * 获取ss表单数据
     *
     * @param id ssID
     * @return
     */
    @Override
    public ExamsForm getExamsFormData(Long id) {
        Exams entity = this.getById(id);
        return null;
    }

    /**
     * 新增ss
     *
     * @param formData ss表单对象
     * @return
     */
    @Override
    public boolean saveExams(ExamsForm formData) {

        return false;
    }

    /**
     * 更新ss
     *
     * @param id   ssID
     * @param formData ss表单对象
     * @return
     */
    @Override
    public boolean updateExams(Long id,ExamsForm formData) {
        return false;
    }

    /**
     * 删除ss
     *
     * @param ids ssID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteExams(String ids) {
//        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的ss数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();


        return this.removeByIds(idList);
    }
    @Override
    public List<ExamDto> returnExamsData(int page, int size) {

        // 创建分页对象
        Page<Exams> videoPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Exams> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Exams::getOpenType, 5);
        // 使用 MyBatis-Plus 的分页查询
        IPage<Exams> pagedExams = this.page(videoPage, lambdaQueryWrapper);


        List<Exams> examList = pagedExams.getRecords();
        if (examList==null){
            throw new CustomException(0,"错误");
        }
        List<ExamDto>  examDtoList= examList.stream().map(exam -> {
            ExamDto examDto = new ExamDto();
            examDto.setId(exam.getId());
            examDto.setName(exam.getTitle());

            examDto.setDuration(getTime(Long.valueOf(exam.getDuration())));
            examDto.setTotalScore(exam.getTotalScore());
            examDto.setPassScore(exam.getPassScore());
            examDto.setStatus(getStatus(exam.getStartTime(), exam.getEndTime()));

            examDto.setStartTime(DateTimeUtils.formatDateTime(exam.getStartTime(),DATE_FORMAT));
            examDto.setEndTime(DateTimeUtils.formatDateTime(exam.getEndTime(),DATE_FORMAT));

            return examDto;
        }).collect(Collectors.toList());

        return examDtoList;
    }

    @Override
    public Boolean submitExam( ExamSubmitDto examSubmitDto) {

       Boolean bo= redisService.hasKey("exam:"+SecurityUtils.getCurrentUserId());

       if (!bo){
           throw new CustomException(1500,"非法数据提交，或数据错误");
       }

        examSubmitDto.getId();
        return null;
    }





















    public  String getTime(Long minutes) {
        if (minutes < 60) {
            return minutes + "分钟"; // 小于60分钟直接显示分钟
        } else {
            long hours = minutes / 60; // 计算小时
            long remainingMinutes = minutes % 60; // 计算剩余的分钟
            return hours + "小时" + String.format("%02d", remainingMinutes) + "分钟"; // 格式化分钟为两位数
        }
    }
    public int getStatus(LocalDateTime startTime, LocalDateTime endTime) {
        LocalDateTime now = LocalDateTime.now();

        if (now.isBefore(startTime)) {
            return 1; // 当前时间在开始时间之前
        } else if (!now.isAfter(endTime)) {
            return 2; // 当前时间在开始时间和结束时间之间（包括开始和结束时间）
        } else {
            return 3; // 当前时间在结束时间之后
        }
    }
}